package com.xiaobias.distributed.pan.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import java.io.File;
import java.util.List;
import java.util.Map;

public class HttpTool {

    public static long downloadFile(String url, File destFile, Map<String, List<String>> headers, StreamProgress streamProgress) {
        return downloadFile(url, destFile, headers, -1, streamProgress);
    }

    public static long downloadFile(String url, File targetFileOrDir, Map<String, List<String>> headers, int timeout, StreamProgress streamProgress) {
        if (!targetFileOrDir.exists()) {
            FileUtil.touch(targetFileOrDir);
        }
        return requestDownload(url, headers, timeout).writeBody(targetFileOrDir, streamProgress);
    }

    /**
     * 请求下载文件
     *
     * @param url     请求下载文件地址
     * @param timeout 超时时间
     * @return HttpResponse
     * @since 5.4.1
     */
    private static HttpResponse requestDownload(String url, Map<String, List<String>> headers, int timeout) {
        Assert.notBlank(url, "[url] is blank !");

        final HttpResponse response = HttpUtil.createGet(url, true)
                .timeout(timeout)
                .header(headers)
                .executeAsync();

        if (response.isOk()) {
            return response;
        }

        throw new HttpException("Server response error with status code: [{}]", response.getStatus());
    }
}
